package com.bfs.service.hystrix.collaspers;/**
 * @Deacription TODO
 * @Author baohuajie
 * @Date 2020/12/13 23:15
 * @Version 1.0
 **/

import com.netflix.hystrix.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *@Deacription TODO
 *@Author baohuajie
 *@Date 2020/12/13 23:15
 *@Version 1.0
 **/
public class HystrixCommandSingle extends HystrixCommand<String> {

    private final Logger log = LoggerFactory.getLogger(HystrixCommandSingle.class);

    private QueryService queryService;
    private String id;

    public HystrixCommandSingle( QueryService queryService, String id) {
        super(setter());
        this.queryService = queryService;
        this.id = id;
    }

    @Override
    public String run() throws Exception {
        return queryService.querySingle(id);
    }

    @Override
    protected String getFallback() {
        log.info("=========getFallback:{}=========", Thread.currentThread().getName());
        return super.getFallback();
    }

    /**
     * 熔断器设置
     * @return
     */
    private static Setter setter(){
        HystrixCommandKey hystrixCommandKey = HystrixCommandKey.Factory.asKey("queryCommandKey");
        HystrixCommandGroupKey hystrixCommandGroupKey = HystrixCommandGroupKey.Factory.asKey("queryCommandGroupKey");
        HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("queryThreadPoolKey");
        HystrixThreadPoolProperties.Setter threadPoolSetter = HystrixThreadPoolProperties.Setter().withCoreSize(10)
                .withMaximumSize(20)
                .withMaxQueueSize(30)
                .withQueueSizeRejectionThreshold(30);
        HystrixCommandProperties.Setter propertiesSetter = HystrixCommandProperties.Setter().withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)
                .withExecutionTimeoutEnabled(true)
                .withExecutionTimeoutInMilliseconds(40000);


        Setter setter = Setter.withGroupKey(hystrixCommandGroupKey)
                .andCommandKey(hystrixCommandKey)
                .andThreadPoolKey(threadPoolKey)
                .andThreadPoolPropertiesDefaults(threadPoolSetter)
                .andCommandPropertiesDefaults(propertiesSetter);
        return setter;
    }
}
